package com.bonc.controller;

import com.bonc.ProjectConstant;
import com.bonc.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/search")
public class SearchController  implements ApplicationContextAware {
	@Autowired
	SearchService sService;

	// 添加信息，跳转搜索
	@RequestMapping({"/addInfo"})
	public String addInfo(String info) {
		sService.addInfo(info, false);
		return "SUCCESS";
	}

	@RequestMapping({"","/search"})
	public String search(String cond) {
		saveCond(cond);
		String result = sService.searchInfo(cond);
		return result;
	}

	private void saveCond(String cond){
		try {
			// target文件夹
//			File file = ResourceUtils.getFile(ProjectConstant.CONDITION_FILE);
			File file = new File(ProjectConstant.CONDITION_FILE);
			if(!file.exists()){
				file.createNewFile();
			}
			Files.write(file.toPath(), Arrays.asList(cond));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping({"test"})
	public String test(String cond) {
		return cond;
	}

	@RequestMapping({"/addAndSearch"})
	public String addAndSearch(String info, String cond) {
		saveCond(cond);
		sService.addInfo(info, false);
		return sService.searchInfo(cond);
	}

	@RequestMapping({"/addFileAndSearch"})
	public String addFileAndSearch(int lines, String cond) throws Exception {
		saveCond(cond);
		String info = getFileContent(lines, "拯救购物困难患者④.txt");
		if(StringUtils.isBlank(info)){
			log.warn("file content is empty");
		}else{
			log.info(info.substring(Math.max(0, info.length()-100)));
		}
		sService.addInfo(info, true);
		return sService.searchInfo(cond);
	}

	private String getFileContent(int lines, String fileName) throws IOException {
		File file = new File("C:\\Users\\Administrator\\Desktop\\"+fileName);
		log.info("file path={}, exist={}", file.getAbsolutePath(), file.exists());
		// idea中正常，打包后异常
		String content = "";
		if(file.exists()){
//			content = getStringBuilder(lines, file);
			content = getStringBuilder(lines, file);
		}
		return content;
	}

	// idea中正常，打包后异常
	private String getStringBuilder(int lines, File file) throws IOException {
		StringBuilder builder = new StringBuilder();
		// 读取为"iso-8859-1"
		RandomAccessFile raf = new RandomAccessFile(file, "r");
		long seek = file.length() - lines *200;// 每个记录预计200byte
		raf.seek(seek);
		String line = raf.readLine();
		boolean removeFirst = true;
		log.info("System file.encoding={}", System.getProperty("file.encoding"));
		while (line!=null){
			log.info("before; {}", line);
			line = new String(line.getBytes("iso-8859-1"), StandardCharsets.UTF_8);
			log.info(line);
			builder.append(line).append("\n");
			if(removeFirst && StringUtils.isBlank(line)){
				builder = new StringBuilder("");
				removeFirst = false;
			}
			line = raf.readLine();
		}
		return builder.toString();
	}

	private String getStringBuilder2(int lines, File file) throws IOException {
		List<String> content = Files.readAllLines(file.toPath());
		if(CollectionUtils.isEmpty(content)){
			return "";
		}
		int size = content.size();
		content = content.subList(Math.max(0, size - lines), size);
		return content.stream().collect(Collectors.joining("\n"));
	}


	@RequestMapping("/getCondition")
	public String getCondition() throws IOException {
//		Resource resource = applicationContext.getResource(ProjectConstant.CONDITION_FILE);
//		InputStream inputStream = resource.getInputStream();
		File file = new File(ProjectConstant.CONDITION_FILE);
		if(!file.exists()){
			file.createNewFile();
		}
		InputStream inputStream = new FileInputStream(file);
		byte[] bytes = new byte[1024];
		int len;
		StringBuilder builder = new StringBuilder();
		do{
			len = inputStream.read(bytes);
			if(len>0){
				builder.append(new String(bytes, 0, len, StandardCharsets.UTF_8));
			}
		}while (len>=1024);
		return builder.toString();
	}

	private ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public static void main(String[] args) throws IOException {
		List<String> list = Files.readAllLines(Paths.get("C:\\Users\\Administrator\\Desktop\\", "拯救购物困难患者④.txt"));
		System.out.println(list.get(1234));
	}
}
